<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//资产管理
class Assets extends CommonController {

	function __construct(){
		
		parent::__construct();
		$this->load->model('Accounting/AssetsModel','CurModel');
		
	}
	
	
	//start
	/**
	* @name 获取列表
	* @param page ture char 页面
	* @param size ture char 数量
	* @return 成功返回1
	*/
	//end
	function get_list(){
		$user_id = $this->user_id;
		
		if(!$this->check_priv('accounting_assets|accounting_assets_1')){
			$this->err_out(LANG_NOPRIV);
		}
		
		$page = $this->input->post('page',null,1);
		$size = $this->input->post('size',null,10);
		
		$filter = $this->input->post('f',null,array());
		
		
		$res = $this->CurModel->get_list($filter,$page,$size);
		$list = $res['list'];
		
		foreach($list as $key=>$val){
			$list[$key]['balance'] = 0;

			if($list[$key]['start_date'] == '0000-00-00'){
				$list[$key]['start_date'] = '';
			}
			if($list[$key]['end_date'] == '0000-00-00'){
				$list[$key]['end_date'] = '';
			}

			
			if($val['status']==2){//折旧完成
				$list[$key]['balance'] = 0;
			}else if($val['status']==1){//报废
				$month_num = $this->getMonthNum($val['start_date'],date('Y-m-d'));
				$balance = $val['money'] - ($month_num * $val['depreciation']);//正常累计折旧期末余额
				$list[$key]['depreciation'] = $val['depreciation'] + $balance;
				$list[$key]['balance'] = 0;
				//$list[$key]['depreciation'] = $list[$key]['depreciation']+($list[$key]['money']-$month_num*$list[$key]['depreciation']);
			}else{//在用
				$month_num = $this->getMonthNum($val['start_date'],date('Y-m-d'));
				$balance = $val['money'] - ($month_num * $val['depreciation']);
				$list[$key]['balance'] = ($balance > 0)?$balance:0;
			}
			
		}
		$res['list'] = $list;
		
		$this->data_out($res);
	}
	
	function date_cl($cstart,$useful_life){
		$start = strtotime($cstart);
		$end = strtotime("+{$useful_life} year",$start);
		
		
		$result = $this->getMonthNum($cstart,date('Y-m-d',$end));
		return $result;
	}
	
	function getMonthNum($date1,$date2){
		$date1_stamp=strtotime($date1);
		$date2_stamp=strtotime($date2);
		list($date_1['y'],$date_1['m'])=explode("-",date('Y-m',$date1_stamp));
		list($date_2['y'],$date_2['m'])=explode("-",date('Y-m',$date2_stamp));
		return abs(($date_2['y']-$date_1['y'])*12 +$date_2['m']-$date_1['m']);
	}
	
	
	function info_out($info){
		
		return $info;
	}
	
	
	//start
	/**
	* @name 引入资产
	* @param date ture char 日期开始和结束
	* @return 成功返回1
	*/
	//end
	function yinru(){
		
		if(!$this->check_priv('accounting_assets_2')){
			$this->err_out(LANG_NOPRIV);
		}
		
		$filter = $this->input->post('f',null,array());
		if(empty($filter['date'])){
			$this->err_out('请选择月份');
		}
		
		$fg = explode('|',$filter['date']);
		if(count($fg)<2){
			$this->err_out('错误的日期时间');
		}
		$start = $fg[0];
		$end = $fg[1];
		
		$farr = array('type','region','company','bumen','subject');
		$arr = array();
		foreach($filter as $key=>$val){
			if(in_array($key,$farr)){
				$arr[$key] = $val;
			}
		}
		
		$arr['start'] = $start;
		$arr['end'] = $end;
		
		
		$result = $this->CurModel->yinru_data($arr);
		if(!$result){
			$this->err_out('引入数据错误');
		}
		$this->data_out(1);
		
	}
	
	
	//start
	/**
	* @name 获取信息
	* @param id ture char ID
	* @return 成功返回1
	*/
	//end
	function get_info(){
		$user_id = $this->user_id;
		
		$result = parent::_get_info();
		if(!$result){
			$this->err_out($this->getError());
		}
		
		$this->data_out($result);
	}
	
	
	
	
	//start
	/**
	* @name 获取信息
	* @param id ture char ID
	* @return 成功返回1
	*/
	//end
	function save(){
		
		if(!$this->check_priv('accounting_assets_2')){
			$this->err_out(LANG_NOPRIV);
		}
		
		
		$id = $this->input->post('id',null,0);
		$info = $this->CurModel->get_info($id);
		
		if(!$info){
			$this->err_out('数据不存在');
		}
		
		$filter = array(
			'assets_no'=>'资产编号不能为空',
			//'depreciation'=>'累计折旧余额不能为空',
			'user'=>'使用人不能为空',
			'name'=>'固定资产名称不能为空',
			'num'=>'单位不能为空',
			'start_date'=>'请选择取得日期',
			'end_date'=>'请选择截止日期',
		);
		$post = array('assets_no','user','name','num','start_date','end_date','status');
		$farr = array(
			'post'=>$post,
			'filter'=>$filter
		);
		
		$check_result = parent::_checkData($farr);
		if(!$check_result){
			$this->err_out($this->getError());
		}
		
		$time = time();
		
		
		// $month_num = $this->getMonthNum($_POST['start_date'],$_POST['end_date']);
		// if($month_num<=0){
		// 	$this->err_out('日期之间不能小于1个月');
		// }
		$month_num = $_POST['useyear']*12 + $_POST['usemonth'];
		$depreciation = $info['money'] / $month_num ;
		
		$useyear = intval($month_num/12);
		$usemonth = $month_num%12;
		
		$append_arr = array(
			'addtime'=>$time,
			'depreciation'=>$depreciation,
			'useyear'=>$useyear,
			'usemonth'=>$usemonth
		);
		
		$result = parent::_save($farr,$append_arr,true);
		if(!$result){
			$this->err_out($this->getError());
		}
		
		$this->add_log("保存资产【{$result['id']}】信息",'role');
		
		$this->data_out($result);
	}
	
	//start
	/**
	* @name 删除
	* @param id ture int ID
	* @return 成功返回1
	*/
	//end
	function del(){
		
		
		if(!$this->check_priv('accounting_assets_2')){
			$this->err_out(LANG_NOPRIV);
		}
		
		$result = parent::_del();
		if(!$result){
			$this->err_out($this->getError());
		}
		
		$this->add_log("删除资产【{$result}】信息",'role');
		$this->data_out($result);
		
	}
	//start
	/**
	* @name 设置状态
	* @param id ture int ID
	* @param status ture int 状态
	* @return 成功返回1
	*/
	//end
	function set_status(){
		if(!$this->check_priv('accounting_assets_2')){
			$this->err_out(LANG_NOPRIV);
		}
		
		$id = $this->input->post('id',null,0);
		$status = $this->input->post('status',null,0);
		
		if(!in_array($status,array(0,1,2))){
			$this->err_out('参数错误');
		}
		$info = $this->CurModel->get_info($id);
		if(!$info){
			$this->err_out('数据不存在');
		}
		if($info['status']==$status){
			$this->err_out('该资产信息状态已经设置');
		}
		
		
		$time = time();
		$arr = array(
			'status'=>$status
		);

		
		// if($status==1){
		// 	$month_num = $this->getMonthNum($info['start_date'],date('Y-m-d'));
		// 	if($month_num>0){
		// 		$mm = $month_num * $info['depreciation'] ;
		// 	}
		// 	else{
		// 		$mm = 0 ;
		// 	}
		// 	$balance = $info['money'] - $mm;
		// 	$arr['depreciation'] = $info['depreciation'] + $balance;
		// }
		// else{
		// 	$month_num = $this->getMonthNum($info['start_date'],$info['end_date']);
			
		// 	if($month_num>0){
		// 		$depreciation = $info['money'] / $month_num ;
		// 	}
		// 	else{
		// 		$depreciation = 0 ;
		// 	}
		// 	$arr['depreciation'] = $depreciation;
		// }
		
		$this->CurModel->edit($arr,"id='{$id}'");
		
		$this->add_log("设置资产【{$id}】状态",'role');
		$this->data_out(1);
	}
	
	//start
	/**
	* @name 批量操作
	* @param ids ture int_array ID组合
	* @param act ture int 操作类型enable，disconnected，delete
	* @return 成功返回1
	*/
	//end
	function batch_act(){
		
		if(!$this->check_priv('accounting_assets_2')){
			$this->err_out(LANG_NOPRIV);
		}
		
		$ids = $this->input->post('ids',null,array());
		$act = $this->input->post('act',null,'');
		
		$act_arr = array('baofei','zaiyong','zhejiu_ok','delete');
		if(!in_array($act,$act_arr)){
			$this->err_out('错误的错误');
		}
		if(!is_array($ids)){
			$ids = explode(',',$ids);
		}
		if(count($ids)<=0){
			$this->err_out('请选择成员');
		}
		$ls_ids = array();
		foreach($ids as $id){
			if(!empty($id)){
				$ls_ids[] = $id;
			}
		}
		
		if($act=='delete'){
			$this->CurModel->del("id in(".implode(',',$ls_ids).")");
		}
		else{
			$res = $this->CurModel->getAll("id in(".implode(',',$ls_ids).")");
			foreach($res as $key=>$val){
				if($act=='baofei'){
					$arr = array('status'=>1);
					
					$month_num = $this->getMonthNum($val['start_date'],date('Y-m-d'));
					
					if($month_num>0){
						$mm = $month_num * $val['depreciation'] ;
					}
					else{
						$mm = 0 ;
					}
					
					$balance = $val['money'] - $mm;
					$arr['depreciation'] = $val['depreciation'] + $balance;
					
					$this->CurModel->edit($arr,"id ='{$val['id']}'");
				}
				elseif($act=='zaiyong'){
					
					$arr = array('status'=>0);
					$month_num = $this->getMonthNum($val['start_date'],$val['end_date']);
					if($month_num>0){
						$depreciation = $val['money'] / $month_num ;
					}
					else{
						$depreciation = 0 ;
					}
					
					$arr['depreciation'] = $depreciation;
					$this->CurModel->edit($arr,"id ='{$val['id']}'");
				}
				elseif($act=='zhejiu_ok'){
					
					$arr = array('status'=>2);
					$month_num = $this->getMonthNum($val['start_date'],$val['end_date']);
					if($month_num>0){
						$depreciation = $val['money'] / $month_num ;
					}
					else{
						$depreciation = 0 ;
					}
					$arr['depreciation'] = $depreciation;
					$this->CurModel->edit($arr,"id ='{$val['id']}'");
				}
			}
		}
		
		$this->data_out(1);
	}
	
	//start
	/**
	* @name 导出数据
	* @return 成功返回1
	*/
	//end
	function export_data(){
		$user_id = $this->user_id;
		
		if(!$this->check_priv('accounting_assets|accounting_assets_1')){
			$this->err_out(LANG_NOPRIV);
		}
		
		
		
		$filter = $this->input->post('f',null,array());
		$name = $this->input->post('name',null,'');
		
		$list = $this->CurModel->get_all($filter);
		
		
		foreach($list as $key=>$val){
			$list[$key]['balance'] = 0;
			
			if($val['status']==0){
				$month_num = $this->getMonthNum($val['start_date'],date('Y-m-d'));
				$balance = $val['money'] - ($month_num * $val['depreciation']);
				$list[$key]['balance'] = $balance?$balance:0;
			}
		}
		$status_arr = array('在用','报废','折旧完成');
		
		$colunms = array(
			'assets_no'=>'固定资产编号',
			'company'=>'公司主体',
			'bumen'=>'部门',
			'region'=>'地区',
			'user'=>'使用人',
			'name'=>'固定资产名称',
			'num'=>'单位',
			'start_date'=>'取得时间',
			'end_date'=>'截止时间',
			'useyear'=>'使用年限',
			'money'=>'固定资产原值',
			
			'depreciation'=>'应提折旧',
			'balance'=>'累计折旧期末余额',
			'status'=>'使用状态',
		); 
		
		$arr = array();
		$line = 1;
		
		$arr['A'.$line] =  $name;
		$line++;
		$ls_index = 0;
		foreach($colunms as $key=>$val){
			$ls_col = $this->get_char($ls_index,'A');
			$arr[$ls_col.$line] = $val;
			$ls_index++;
		}
		$line++;
		foreach($list as $key=>$val){
			$ls_index = 0;
			foreach($colunms as $k=>$v){
				$ls_col = $this->get_char($ls_index,'A');
				$ls_val = $val[$k];
				
				if($k=='status'){
					$ls_val = $status_arr[$ls_val];
				}
				elseif($k=='useyear'){
					$txt = '';
					if($val['useyear']>0){
						$txt .= $val['useyear'] . '年';
					}
					$txt .= $val['usemonth'] .'个月';
					$ls_val = $txt;
				}
				
				
				
				$arr[$ls_col.$line] = $ls_val;
				$ls_index++;
			}
			
			$line++;
		}
		
		

		
		$result = $this->Excel_write($arr);
		if(!$result){
			$this->err_out('生成Excel文件失败');
		}
		
		$url = base_url($result);
		
		$this->data_out($url);
	}
	
	function get_char($num,$pos='A'){
		if($num==0){
			return $pos;
		}

		for($i=0;$i<$num;$i++){
			$pos++;
		}
		return $pos;
	}
	
	function Excel_write($data,$merges=array()){
		$this->load->library('PHPExcel');
		
		// 创建Excel文件对象
		$objPHPExcel = new PHPExcel();
		// 设置文档信息，这个文档信息windows系统可以右键文件属性查看
		$objPHPExcel->getProperties()->setCreator("作者lalala")
			->setLastModifiedBy("最后更改者")
			->setTitle("文档标题")
			->setSubject("文档主题")
			->setDescription("文档的描述信息")
			->setKeywords("设置文档关键词")
			->setCategory("设置文档的分类");
		
		$objPHPExcel->setActiveSheetIndex(0);

		
									
		
		$objPHPExcel->getActiveSheet()->getStyle('A3')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER)->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('B3')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER)->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		
		foreach($data as $key=>$val){
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue($key,$val);
		}
		
		foreach($merges as $key=>$val){
			$objPHPExcel->setActiveSheetIndex(0)->mergeCells($val);
		}
		
		$objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel ->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex(0))->setAutoSize(true); 
		//$objPHPExcel->getActiveSheet()->setTitle('第一个sheet');

		// 设置第一个sheet为工作的sheet
		

		// 保存Excel 2007格式文件，保存路径为当前路径，名字为export.xlsx
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		$time = time();
		$dir  =  'upload/res/upload/other/'.date('Ymd');
		if(!is_dir(FCPATH . $dir)){
			@mkdir(FCPATH . $dir);
		}
		
		$file_name = $time.'_'.rand(10000,99999).'.xlsx';
		$objWriter->save(FCPATH . $dir .'/' .$file_name);
		
		return $dir .'/' .$file_name;
	}
}
